<?php
uses('sanitize');
vendor('class-IXR','utility', 'gersh_constants');
class PostsController extends AppController {

	var $name = 'Posts';
	
	var $uses = array('Post');
	var $helpers = array('Html', 'Form', 'Javascript', 'Ajax', 'Time', 'Text', 'Cache');
	var $components = array('RequestHandler'); //, 'WpBlogApi'
	
	//var $cacheAction = "1 hour";
	var $cacheAction = array(
	    'index'  => "1 hour",
	    'browse'  => "1 hour",
		'getalltags' => "1 hour",
		'resentposts' => "1 hour"
	);


	/* Private functions used in this controller */
	function _ping($server = '', $path = '') {
		//return "debug";
		// using a timeout of 3 seconds should be enough to cover slow servers
		$client = new IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
		$client->timeout = 3;
		$client->useragent .= ' -- gBlog';
		// http://localhost/~gersh
		// when set to true, this outputs debug messages by itself
		//$client->debug = false;
		if ( !$client->query('weblogUpdates.extendedPing', $this->Post->blog_settings['blogname'], $this->Post->blog_settings['siteurl'], $this->Post->blog_settings['rss2_url'] ) ) // then try a normal ping
			$client->query('weblogUpdates.ping', $this->Post->blog_settings['blogname'], $this->Post->blog_settings['siteurl']);
		//pr($client->getResponse());
		$response = $client->getResponse();
		return $response['message'];
	}
		
	function _search($prefix = '/admin', $query = null, $page = 1) { 

			if(empty($this->data) and $query == null) { 
				$this->Session->setFlash('Please enter a query.');
			} else { 
				if($query == null) {
					$search_term = $this->data['Post']['body'];
					$this->redirect($prefix . '/posts/search/' . $search_term);
				} 
				$search_term = $query; 

				$limit_posts = POST_LIMIT_BACKEND;
				$post_condition = "Post.body LIKE '%$search_term%' OR Post.title LIKE '%$search_term%'";
				if($prefix != '/admin') {
					$limit_posts = POST_LIMIT_FRONT;
					$post_condition = POST_CONDITION . " and " . $post_condition;
				}

				$num_posts = $this->Post->findCount($post_condition, 1);
				$posts = $this->Post->findAll($post_condition, null, POST_ORDER, $limit_posts, $page, 1 );
				if(count($posts) > 0) $this->Session->setFlash('Your query "' . $query . '" gave ' . $num_posts . ' matches!');
				else $this->Session->setFlash('Your query gave none matches!');
				//Set output variables
				$this->set('posts', $posts); 
				$this->data['Post']['body'] = $query;
				$this->set('pages', $this->calculatePages('Post', $page, $limit_posts, $post_condition ));
				$this->set('this_page', $page);
				$this->set('query', $query);
			} 
		}
	/* Ajax functions */
	function getalltags() {
	    $this->set('tags', $this->Post->findDistinctTags());
		// $ajax_request controlls if list in view should be links or not
		if($this->RequestHandler->isAjax()) $this->set('ajax_request', true);
	}
	
	function resentposts($num = 10) {
		$this->set('posts', $this->Post->findAll(POST_CONDITION, null, POST_ORDER, $num) );
	}
		
	function rss(){
		$this->layout = 'xml';
 		$posts = $this->Post->findAll(POST_CONDITION, null, POST_ORDER, 10, null, 0 );
		$san = new Sanitize(); 
		foreach($posts as $post) {
			$posts[$g]['Post']['body'] = $san->html($post['Post']['body']);
		}
		$this->set('posts', $posts);
	}
	
	
	function index() {
		//$post = $this->Post->read(null, 155);
		//pr($post);
		$this->checkCookie();
		$this->browse();
		$this->pageTitle = 'Homepage';
		$this->render('browse');
		
	}
	
	function browse($page = 1) {
		$san = new Sanitize();
			$page = $san->paranoid($page);
			$this->pageTitle = "Browse $page";
			$this->set('pages', $this->calculatePages('Post', $page, POST_LIMIT_FRONT, POST_CONDITION ));
			$this->set('this_page', $page);
			$posts = $this->Post->findAll(POST_CONDITION, null, POST_ORDER, POST_LIMIT_FRONT, $page, 1 );
			$this->set('posts', $this->Post->addReadMoreTag($posts));
	}
	
	function archive($year = null, $month = null, $slug = null) {
		if (!preg_match("/^[0-9]{4}$/", $year)) {
			$this->redirect('/posts/archive/' . date("Y"));
		}
		
		if($slug == null) {
			// Find all post written in ie 2007
			$this->pageTitle = 'Archived posts written in ' . $year;
			//$this->Session->setFlash($this->pageTitle);
			$date1 = date(MYSQL_DATE, mktime( 0, 0, 0, 1, 1, $year));
			$date2 = date(MYSQL_DATE, mktime( 0, 0, 0, 1, 0, $year+1));
			$post_condition = POST_CONDITION ." and Post.date BETWEEN DATE '$date1' AND DATE '$date2'";
				
			$posts = $this->Post->findAll($post_condition, null, POST_ORDER, null, null, 0 );
			$this->set('archived_posts', $posts);
			$this->set('archived_title', $this->pageTitle);
		} else {
			// Show the single post finded by date and slug
			if(!$post = $this->Post->findBySlug($slug)) {
				$this->Session->setFlash("Can't find a post with that name!");
				$this->redirect('/posts/archive/' . date("Y"));
			}
			$this->pageTitle = $post['Post']['title'];
			$this->set('post', $post);
		}
	}
	
	function search($query = null, $page = 1) { 
		$this->pageTitle = 'Search posts';
		$this->_search(null, $query, $page); 		
		
	}

	function tags($tag = "", $page = 1) {
		$this->pageTitle = "Tags in blogposts";
		if($tag == "") {
			$this->render();
		} else {
		$san = new Sanitize();
		$tag = $san->paranoid($tag);
		$page = $san->paranoid($page);
		$post_condition = POST_CONDITION . ' and Post.tag LIKE "%' . $tag . '%"';
		$num_posts = $this->Post->findCount($post_condition, 1);

		if(count($num_posts) > 0) {
			$pages = array();
			$j = 1;
			for($i=0; $i < $num_posts; $i+=POST_LIMIT_FRONT) {
				$pages[] = $j;
				$j++;
			}
			$posts = $this->Post->findAll($post_condition, null, POST_ORDER, POST_LIMIT_FRONT, $page, 1 );
			$this->Session->setFlash($num_posts . ' post(s) tagged "' . $tag . '" <br /> Viewing page ' . $page . ' of ' . count($pages) . '.');
			$this->pageTitle = "Posts tagged $tag";
			$this->set('tag', $tag);
			$this->set('pages', $pages);
			$this->set('this_page', $page);
			$this->set('posts', $this->Post->addReadMoreTag($posts));
		} else {
			$this->Session->setFlash('No posts tagged "' . $tag . '"');
		}
	}
	}

	/* Back-end functions */
	 
	function admin_search($query = null, $page = 1) { 
		$this->pre_admin();
		
		$this->_search('/admin', $query, $page);
	}
	function admin_index($page = 1) {
		$this->pre_admin();
		/*** Config fetch ***/
		$post_condition = null;
		
		$this->set('pages', $this->calculatePages('Post', $page, POST_LIMIT_BACKEND, $post_condition ));
		$this->set('this_page', $page);

		$posts = $this->Post->findAll($post_condition, null, POST_ORDER, POST_LIMIT_BACKEND, $page, 1 );
		$this->set('posts', $posts);
	}
	
	function admin_addedit($id = null) {
		$this->pre_admin();
		$this->set('post_states', array("published"=>"published", "draft"=>"draft", "page"=>"page"));
		if(empty($this->data)) {
			if($id) {
				$this->data = $this->Post->read(null, $id);
				//
				$this->data['Post']['body'] = preg_replace(array('/\&lt;/i', '/\&gt;/i'), array('&amp;lt;', '&amp;gt;'), $this->data['Post']['body']);
			} else {
				$this->data['Post']['date'] = date(MYSQL_DATE);
				$the_user = $this->Post->User->find(array("User.username" => "admin"), "User.id", null, 0);
				
				$this->data['Post']['user_id'] = $the_user['User']['id'];
				$this->render();
			}
		} else {
			// Saving data, same for new and edit..
			$this->cleanUpFields();
			//$this->data['Post']['body'] = htmlspecialchars($this->data['Post']['body']);
			if($this->Post->save($this->data)) {
				$this->Session->setFlash('The Post has been saved!');
				
				if(!$this->data['Post']['id']) {
					$new_id = $this->Post->getInsertID();
					$ping_response = $this->_ping('rpc.technorati.com', '/rpc/ping'); // http://rpc.pingomatic.com/
					$this->Session->setFlash('The *NEW* Post has been created and saved, and pinged: ' . $ping_response);
					$this->redirect('/admin/posts/addedit/' . $new_id);
				}
				$this->redirect('/admin/posts/addedit/' . $this->data['Post']['id']);
			} else {
				$this->Session->setFlash('Please correct errors below.');
			}
		}
	}

	function admin_delete($id = null) {
		$this->pre_admin();
		if(!$id) {
			$this->Session->setFlash('Invalid id for Post');
			$this->redirect('/admin/posts/index');
		}
		if($this->Post->del($id)) {
			$this->Session->setFlash('The Post deleted: id '.$id.'');
			$this->redirect('/admin/posts/index');
		}
	}

}
?>